package com.kly.sc.api.application.service.product.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.google.common.collect.Lists;
import com.kly.dto.ProductBenefitDto;
import com.kly.dto.ProductDto;
import com.kly.enums.ProductCategory;
import com.kly.enums.ProductStatus;
import com.kly.sc.api.application.controller.product.response.WelcomePackPopVO;
import com.kly.sc.api.application.enums.SwitchTypeEnum;
import com.kly.sc.api.application.remote.UserSwitchManageRemoteService;
import com.kly.sc.api.application.remote.req.SwitchManageListReq;
import com.kly.sc.api.application.service.product.ProductApiService;
import com.kly.sc.api.application.utils.Result;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.sc.api.infras.app.RequestBasicInfo;
import com.kly.service.OrderFacadeService;
import com.kly.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductApiServiceImpl implements ProductApiService {
    @NacosValue(value = "${newcomer.welcomepack.pop}", autoRefreshed = true)
    private String welcomePackPop;
    @Resource
    private OrderFacadeService orderFacadeService;
    @Resource
    private ProductService productService;
    @Resource
    private UserSwitchManageRemoteService userSwitchManageRemoteService;

    private final static Integer privatePhotoBenefitCode = 2;

    @Override
    public Result<WelcomePackPopVO> newcomerWelcomePack(String userCode, RequestBasicInfo requestBasicInfo) {
        String appCode = requestBasicInfo.getAppCode();
        log.info("[新手礼包弹窗]newcomerWelcomePack-{}-step0. {}", userCode, appCode);

        // 用户已有过充值行为不再弹窗
        Response<Integer> resp = orderFacadeService.countPaid(userCode);
        log.info("[新手礼包弹窗]newcomerWelcomePack-{}-step1. {}, {}", userCode, appCode, JSON.toJSONString(resp));
        if (resp == null || !resp.isSuccess() || resp.getData() > 0) {
            return Result.ok();
        }

        // 检查新手惊喜礼包（默认已配置且有效）
        Response<List<ProductDto>> productResp = productService.queryProductsByProductCategory(appCode, ProductCategory.SURPRISE_EASTER_EGG.getCode());
        log.info("[新手礼包弹窗]newcomerWelcomePack-{}-step2. {}, {}", userCode, appCode, JSON.toJSONString(productResp));
        if (productResp == null || !productResp.isSuccess() || CollectionUtils.isEmpty(productResp.getData())) {
            return Result.ok();
        }

        Optional<ProductDto> product = productResp.getData().parallelStream().filter(item -> ProductStatus.ENABLE.getStatus() == item.getStatus()).findAny();
        if (!product.isPresent()) {
            return Result.ok();
        }

        boolean ppvHideFlag = userSwitchManageRemoteService.getSwitch(SwitchManageListReq.from(SwitchTypeEnum.PP_PV, requestBasicInfo));
        log.info("[新手礼包弹窗]newcomerWelcomePack-{}-step3. {}, {}", userCode, appCode, ppvHideFlag);

        WelcomePackPopVO vo = JSON.parseObject(welcomePackPop, WelcomePackPopVO.class);
        vo.setProductCode(product.get().getProductCode());
        vo.setNewcomerPrice("$"+ product.get().getPrice());
        vo.getMemberInfo().setPrice("$"+ product.get().getPrice() + "/day");
        vo.setProductCategory(product.get().getProductCategory());
        final List<ProductBenefitDto> productBenefits = getProductBenefit(appCode, ppvHideFlag);
        vo.getBenefitsInfo().setNum(String.valueOf(getPrivatePhotoNums(productBenefits)));
        vo.setCarousel(WelcomePackPopVO.CarouselImg.from(productBenefits));
        // ppv前端隐藏开关（0 false 展示； 1 true 隐藏），true，不展示ppv赠送信息
        if (ppvHideFlag) {
            vo.setBenefitsInfo(null);
        }

        log.info("[新手礼包弹窗]newcomerWelcomePack-{}-step4. {}, {}", userCode, appCode, JSON.toJSONString(vo));
        return Result.ok(vo);
    }

    private Integer getPrivatePhotoNums(List<ProductBenefitDto> productBenefits) {
        if (CollectionUtils.isEmpty(productBenefits)) {
            return 0;
        }
       return  productBenefits.parallelStream().filter(
               o -> o.getBenefitCode().equals(privatePhotoBenefitCode))
               .map(ProductBenefitDto::getLimitQuantity).findFirst().orElse(0);
    }

    /**
     * 获取新手惊喜礼包权益配置
     */
    private List<ProductBenefitDto> getProductBenefit(String appCode, boolean ppvHideFlag) {
        final List<ProductBenefitDto> productBenefitList = RpcUtils.getResult(
                productService.listProductBenefit(appCode, ProductCategory.SURPRISE_EASTER_EGG.getCode()));
        if (CollectionUtils.isEmpty(productBenefitList)) {
            return Lists.newArrayList();
        }
        // ppv前端隐藏开关（0 false 展示； 1 true 隐藏），true，过滤掉轮播图（showFlag==1）
        if (ppvHideFlag) {
            return productBenefitList.stream().filter(item -> item.getShowFlag() == 1).collect(Collectors.toList());
        }
        return productBenefitList;
    }
}
